// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import LoginView from '../views/LoginView.vue';
import RegisterView from '../views/RegisterView.vue';
import AboutView from '../views/AboutView.vue';
import StartView from '../views/StartView.vue';
import AllTasksView from '../views/AllTasksView.vue'; // 引入新视图
import { useUserStore } from '../userStore';

const routes = [
  {
    path: '/',
    redirect: '/start'
  },
  {
    path: '/start',
    component: StartView
  },
  {
    path: '/home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    component: LoginView
  },
  {
    path: '/register',
    component: RegisterView
  },
  {
    path: '/about',
    component: AboutView
  },
  {
    path: '/all-tasks',
    component: AllTasksView,
    meta: { requiresAuth: true }
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  
  // 检查路由是否需要认证
  if (to.meta.requiresAuth && !userStore.currentUser) {
    // 如果需要认证但用户未登录，重定向到登录页面
    next('/login');
  } else {
    // 允许访问
    next();
  }
});

export default router;